package com.robotic.route.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONObject;
import com.robotic.common.utils.StringUtils;
import com.robotic.common.utils.http.EnhancedHttpUtils;
import com.robotic.kafka.KafkaProducerService;
import com.robotic.minio.MinioService;
import com.robotic.minio.RTSPFrameCaptureWithJavaCV;
import com.robotic.route.service.impl.RoutePointDetailServiceImpl;
import com.robotic.sensor.config.ModbusTcpIoServer;
import com.robotic.tcp.RobotNavigator;
import com.robotic.sensor.service.RobotCoordinateMonitorService;
import com.robotic.udp.RobotService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.robotic.common.annotation.Log;
import com.robotic.common.core.controller.BaseController;
import com.robotic.common.core.domain.AjaxResult;
import com.robotic.common.enums.BusinessType;
import com.robotic.route.domain.RoutePointDetail;
import com.robotic.route.service.IRoutePointDetailService;
import com.robotic.common.utils.poi.ExcelUtil;
import com.robotic.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 路线点位维护Controller
 *
 * @author tian
 * @date 2025-08-21
 */
@Slf4j
@RestController
@RequestMapping("/admin/route")
public class RoutePointDetailController extends BaseController {
    @Autowired
    private IRoutePointDetailService routePointDetailService;

    @Autowired
    private RobotNavigator robotNavigator;

    @Autowired
    private RobotCoordinateMonitorService robotCoordinateMonitorService;

    @Autowired
    private RobotService robotService;

    /**
     * 查询路线点位维护列表
     */
    @GetMapping("/list")
    public TableDataInfo list(RoutePointDetail routePointDetail) {
        startPage();
        List<RoutePointDetail> list = routePointDetailService.selectRoutePointDetailList(routePointDetail);
        return getDataTable(list);
    }

    @GetMapping("/getList")
    public AjaxResult getList(RoutePointDetail routePointDetail) {
        List<RoutePointDetail> list = routePointDetailService.getList(routePointDetail);
        return AjaxResult.success(list);
    }

    /**
     * 导出路线点位维护列表
     */
    @Log(title = "路线点位维护", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RoutePointDetail routePointDetail) {
        List<RoutePointDetail> list = routePointDetailService.selectRoutePointDetailList(routePointDetail);
        ExcelUtil<RoutePointDetail> util = new ExcelUtil<RoutePointDetail>(RoutePointDetail.class);
        util.exportExcel(response, list, "路线点位维护数据");
    }

    /**
     * 获取路线点位维护详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        RoutePointDetail detail = routePointDetailService.selectRoutePointDetailById(id);
        return success(detail);
    }

    /**
     * 新增路线点位维护
     */
    @Log(title = "路线点位维护", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RoutePointDetail routePointDetail) {
        return toAjax(routePointDetailService.insertRoutePointDetail(routePointDetail));
    }

    /**
     * 修改路线点位维护
     */
    @Log(title = "路线点位维护", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RoutePointDetail routePointDetail) {
        return toAjax(routePointDetailService.updateRoutePointDetail(routePointDetail));
    }

    /**
     * 删除路线点位维护
     */
    @Log(title = "路线点位维护", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(routePointDetailService.deleteRoutePointDetailByIds(ids));
    }

    /**
     * 同步路线
     */
    @Log(title = "路线点位维护", businessType = BusinessType.OTHER)
    @GetMapping("/synchro")
    public AjaxResult synchro() {
        int i = routePointDetailService.synchroRoute();
        if (i == 0) {
            return success();
        } else {
            return error();
        }

    }

    /**
     * 下发导航指令
     *
     * @param fileAbsPath 导航路线
     * @return
     */
    @GetMapping("/issueNavigation/{fileAbsPath}")
    public AjaxResult issueNavigation(@PathVariable("fileAbsPath") String fileAbsPath) {
        try {
            if (StringUtils.isEmpty(fileAbsPath)) {
                return AjaxResult.error("请选择线路");
            }
            Future<Integer> integerFuture = routePointDetailService.issueNavigation(fileAbsPath);
            log.info("integerFuture = {}", integerFuture.get());
            if (integerFuture.get() == 1) {
                return success();
            } else {
                return error();
            }
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 下发导航指令
     *
     * @param routePointDetail 导航路线
     * @return
     */
    @GetMapping("/taskNavigation")
    public AjaxResult taskNavigation(RoutePointDetail routePointDetail) {
        int i = routePointDetailService.taskNavigation(routePointDetail);
        if (i == 0) {
            return success();
        } else if (i == -2) {
            return error("请选择于机器人最近的点位作为起点导航");
        } else {
            return error();
        }
    }


    /**
     * 点不点导航
     */
    @PostMapping("/fixedPointNavigation")
    public AjaxResult fixedPointNavigation(@RequestBody RoutePointDetail routePointDetail) {
        if (StringUtils.isEmpty(routePointDetail.getRouteCode()) || StringUtils.isEmpty(routePointDetail.getStartValue())
                || StringUtils.isEmpty(routePointDetail.getEndValue())) {
            return AjaxResult.error("参数异常");
        }
        int i = routePointDetailService.fixedPointNavigation(routePointDetail);
        if (i == 0) {
            return success();
        } else if (i == -2) {
            return error("请选择于机器人最近的点位作为起点导航");
        } else {
            return error();
        }
    }


    /**
     * 取消导航
     */
    @GetMapping("/cancelNavigation")
    public AjaxResult issueNavigation() {
        boolean b = robotNavigator.cancelNavigation();
        if (b) {
            // 取消导航成功后，停止所有坐标监控任务
            try {
                //robotCoordinateMonitorService.stopAllMonitoring();
                log.info("已停止所有机器人坐标监控任务");
            } catch (Exception e) {
                log.error("停止坐标监控任务时发生异常: {}", e.getMessage(), e);
            }
            return success();
        } else {
            return error();
        }
    }

    /**
     * 返航
     */
    @GetMapping("/returnVoyage")
    public AjaxResult returnVoyage() {
        int i = routePointDetailService.returnVoyage();
        if (i == 0) {
            return success();
        } else {
            return error();
        }
    }


    /**
     * 路线查询
     */
    @GetMapping("/getRoute")
    public AjaxResult getRoute() {
        return AjaxResult.success(routePointDetailService.getRoute());
    }

    /**
     * 【新增】 获取机器人连接状态的接口
     *
     * @return 一个包含连接状态的JSON对象, e.g., {"connected": true}
     */
    @GetMapping("/status")
    public AjaxResult getConnectionStatus() {
        boolean status = robotService.isConnected();
        // 使用 Java 8 兼容的方式创建 Map
        Map<String, Boolean> response = new HashMap<>();
        response.put("connected", status);
        return AjaxResult.success(response);
    }

    // 【新增】 连接接口
    @PostMapping("/connect")
    public AjaxResult connect() {
        robotService.connect();
        return AjaxResult.success("Connection initiated.");
    }

    // 【新增】 断开连接接口
    @PostMapping("/disconnect")
    public AjaxResult disconnect() {
        robotService.disconnect();
        return AjaxResult.success("Disconnected from robot.");
    }


    // 通用状态指令接口
    @PostMapping("/command/{command}")
    public AjaxResult executeCommand(@PathVariable String command) {
        robotService.executeStateCommand(command);
        return AjaxResult.success("Command '" + command + "' sent.");
    }

    // 移动指令接口
    @PostMapping("/move")
    public AjaxResult move(@RequestBody Map<String, String> payload) {
        String direction = payload.get("direction");
        if (direction != null && !direction.isEmpty()) {
            robotService.updateMovement(direction);
            return AjaxResult.success("Move '" + direction + "' updated.");
        }
        return AjaxResult.error("Direction is required.");
    }

    // 停止移动接口
    @PostMapping("/stop")
    public AjaxResult stop() {
        robotService.stopMovement();
        return AjaxResult.success("Stop command sent.");
    }

    // 即将执行的任务列表
    @PostMapping("/aboutToExecuteList")
    public AjaxResult aboutToExecuteList() {
        List<Map<String, Object>> list = routePointDetailService.aboutToExecuteList();
        return AjaxResult.success(list);
    }

    // 获取正在执行的任务
    @PostMapping("/getExecutingTask")
    public AjaxResult getExecutingTask() {
        Object executingTask = RoutePointDetailServiceImpl.executingTask;
        return AjaxResult.success(executingTask);
    }



    // 获取正在执行的任务
    @GetMapping("/test1/{ioTYpe}")
    public AjaxResult test1(@PathVariable("ioTYpe") String ioTYpe) {
        ModbusTcpIoServer modbusTcpRelayServer = new ModbusTcpIoServer();
        String s = modbusTcpRelayServer.sendRelayCommand(ioTYpe);
        return AjaxResult.success(s);
    }


    @Autowired
    private KafkaProducerService kafkaProducerService;


    @Autowired
    private RTSPFrameCaptureWithJavaCV rtspFrameCaptureWithJavaCV;


    @Autowired
    private MinioService minioService;

    // 获取正在执行的任务
    @GetMapping("/test2")
    public AjaxResult test2() {
      /*  JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", "1");
        jsonObject.put("workShop", "装配车间");
        jsonObject.put("deviceName", "四足机器人");
        jsonObject.put("pointName", "电箱");
        jsonObject.put("behaviorName", "杂物");
        jsonObject.put("captureTime", System.currentTimeMillis());
        jsonObject.put("backgroundPicUrl", "http://192.168.201.246:9000/safetyimg/math/20251113091957_67_118.png");
        jsonObject.put("model", "吊装带、安全带丟落在地面时进行报警");
        jsonObject.put("pointCode", 1);
        kafkaProducerService.sendMessage(jsonObject.toJSONString());
        MultipartFile multipartFile = rtspFrameCaptureWithJavaCV.captureFrameAsMultipartFile();
        String fileUrl = minioService.uploadFile(multipartFile);*/
        Map<String, String> params = new HashMap<>();
        params.put("menuId", "2");
        params.put("extId", "8110");
        String s = EnhancedHttpUtils.sendPost("http://192.168.201.170:8070/api/phone/voiceCall", params);
        return AjaxResult.success(s);
    }
}
